package com.hemaapp.yjnh.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import xtom.frame.util.XtomToastUtil;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.MapView;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.Client;

/**
 * 在地图上显示周边乐乐商品
 * 
 * @author GuiyouZhang Date：2016年1月8日 下午1:34:53 
 * Email:guiyouzhang@163.com
 */
public class MapActivity extends BaseActivity implements OnMapLoadedListener, AMapLocationListener, 
				OnInfoWindowClickListener, InfoWindowAdapter, LocationSource,
				OnMarkerClickListener{

	private ImageView ivCancel;
	private MapView mapView;

	private ArrayList<Client> clients = new ArrayList<Client>();
	private Map<String, String> ids = new HashMap<String, String>();//用来保存marker的id和商家的id
	private OnLocationChangedListener mListener;
	private AMapLocationClient mlocationClient;
	private AMapLocationClientOption mLocationOption;
	private AMap aMap;
	private String city;
//	private List<Marker> markerlst = new ArrayList<Marker>();
//	private ArrayList<MarkerOptions> markerOptionlst = new ArrayList<MarkerOptions>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_map_lele);
		super.onCreate(savedInstanceState);
		mapView.onCreate(savedInstanceState); // 此方法必须重写
		getClientList();
		if (aMap == null) {
			aMap = mapView.getMap();
			setUpMap();
		}
	}
	
	private void getClientList() {
		getNetWorker().clientList("", "6", city, "1", "1", "6", "0", "", "");
	}

	private void setUpMap() {
		aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
		aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
		aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		// 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
		aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
		aMap.getUiSettings().setZoomControlsEnabled(false);//隐藏缩放控件
//		aMap.setOnMapClickListener(new OnMapClickListener() {
//
//			@Override
//			public void onMapClick(LatLng latlng) {
//				// 根据经纬度去逆地理编码获取地址信息
//				getAddress(latlng.latitude, latlng.longitude);
//			}
//		});
		
//		addMarkersToMap();// 往地图上添加marker
	}
	
	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
		if(null != mlocationClient){
			mlocationClient.onDestroy();
		}
	}
	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case CLIENT_LIST:
			showProgressDialog("请稍候");
			break;
		default:
			break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case CLIENT_LIST:
			cancelProgressDialog();
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case CLIENT_LIST:
			String page = netTask.getParams().get("page");
			@SuppressWarnings("unchecked")
			HemaPageArrayResult<Client> cResult = (HemaPageArrayResult<Client>) baseResult;
			if (cResult == null || cResult.getObjects() == null)
				return;
			if ("0".equals(page)) {// 刷新
				clients.clear();
				clients.addAll(cResult.getObjects());
			}else {
				if (clients.size() > 0)
					this.clients.addAll(cResult.getObjects());
				else {
					XtomToastUtil.showShortToast(mContext, "已经到最后啦");
				}
			}
			//添加坐标到地图上
			addMarkers();
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case CLIENT_LIST:
			XtomToastUtil.showShortToast(mContext, "获取信息失败，"+baseResult.getMsg());
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case CLIENT_LIST:
			XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
			break;
		default:
			break;
		}
	}

	@Override
	protected void findView() {
		ivCancel = (ImageView) findViewById(R.id.iv_cancel);
		mapView = (MapView) findViewById(R.id.map);
		ivCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	protected void getExras() {
		city = mIntent.getStringExtra("city");
	}
	
	private void addMarkers() {
		ids.clear();
		for (Client client:clients) {
			String lat = client.getLat();
			String lng = client.getLng();
			if (isNull(lat) || isNull(lng)) {
				continue;
			}
			LatLng latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
			Marker marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
					.position(latLng).title(client.getNickname())
					.snippet(client.getPrice()).icon(
							BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),
									R.drawable.marker_icon)))
				 .draggable(true));
			ids.put(marker.getId(), client.getClient_id());//将marker的id与client的id一一对应
			marker.showInfoWindow();
			marker.setPosition(latLng);
		}
	}

	/**
	 * 监听amap地图加载成功事件回调
	 */
	@Override
	public void onMapLoaded() {
		// 设置所有maker显示在当前可视区域地图中
//		LatLngBounds bounds = new LatLngBounds.Builder().build();
//		for (Client client:clients) {
//			String lat = client.getLat();
//			String lng = client.getLng();
//			if (isNull(lat) || isNull(lng)) {
//				continue;
//			}
//			LatLng latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
//			bounds.including(latLng);
//		}
//		aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150));
	}

	/**marker上的window的点击事件
	 * 
	 */
	@Override
	public void onInfoWindowClick(Marker marker) {
		//点击后跳转到商家详情
		Intent it = new Intent(mContext, CmnBookMerchantDetailActivity.class);
		it.putExtra("client_id", ids.get(marker.getId()));
		startActivity(it);
	}
	
	/**
	 * 监听自定义infowindow窗口的infocontents事件回调
	 */
	@Override
	public View getInfoContents(Marker marker) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 监听自定义infowindow窗口的infowindow事件回调
	 */
	@Override
	public View getInfoWindow(Marker marker) {
		View infoWindow = getLayoutInflater().inflate(
				R.layout.listitem_lele_map_item, null);
		render(marker, infoWindow);
		return null;
	}
	/**
	 * 自定义infowinfow窗口
	 */
	public void render(Marker marker, View view) {
		String title = marker.getTitle();
		TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
		if (title != null) {
			SpannableString titleText = new SpannableString(title);
			titleText.setSpan(new ForegroundColorSpan(Color.BLACK), 0,
					titleText.length(), 0);
			tv_name.setTextSize(11);
			tv_name.setText(titleText);
		} else {
			tv_name.setText("");
		}
		String Content = "¥"+marker.getTitle()+"起";
		TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
		if (title != null) {
			SpannableString contentText = new SpannableString(Content);
			contentText.setSpan(new ForegroundColorSpan(Color.RED), 0,
					contentText.length(), 0);
			tv_price.setTextSize(11);
			tv_price.setText(contentText);
		} else {
			tv_price.setText("");
		}
	}

	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mlocationClient == null) {
			mlocationClient = new AMapLocationClient(this);
			mLocationOption = new AMapLocationClientOption();
			//设置定位监听
			mlocationClient.setLocationListener(this);
			//设置为高精度定位模式
			mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
			//设置定位参数
			mlocationClient.setLocationOption(mLocationOption);
			// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
			// 在定位结束后，在合适的生命周期调用onDestroy()方法
			// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
			mlocationClient.startLocation();
		}
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		mListener = null;
		if (mlocationClient != null) {
			mlocationClient.stopLocation();
			mlocationClient.onDestroy();
		}
		mlocationClient = null;
	}
	/**
	 * 定位成功后回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		if (mListener != null && amapLocation != null) {
			if (amapLocation != null
					&& amapLocation.getErrorCode() == 0) {
				mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
			} else {
				String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
				Log.e("AmapErr",errText);
				XtomToastUtil.showShortToast(mContext, errText);
			}
		}
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		marker.showInfoWindow();
		return false;
	}
}
